package bar.dark.lee.manager.money;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import bar.dark.lee.BDConstents;
import bar.dark.lee.R;
import bar.dark.lee.SuperActivity;
import bar.dark.lee.common.BDUtil;
import bar.dark.lee.common.DBSQLite;
import bar.dark.lee.common.DBSQLite.ParseSelectData;
import bar.dark.lee.common.EditTextInputFilter;
import bar.dark.lee.manager.card.CheckCardActivity;
import bar.dark.lee.manager.card.CreditCardActivity;

public class BankMoneyActivitiy extends SuperActivity
{
	public final static String BANKBOOK_DATA = "bankbook_data";
	
	public static final String LINK_CARD = "link_card";
	public static final String CARD_ID = "card_id";
	
	private DBSQLite sql;
	private ListView listView;
	private Button insertButton;
	private ArrayList<BankbookData> list;
	private BankBookAdapter adapter;
	
	private BigDecimal bankMoney = BigDecimal.ZERO;
	
	private EditText nameView;
	private EditText moneyView;
	
	private boolean checkCardFlag = false;
	private boolean creditCardFlag = false;
	
	private View resultView;
	
	private String name = "";
	private String money = "";
	
	private BankbookData data;
	
	private int addflag = -1;
	private int order = -1;
	private int linkid = -1;
	
	private int detailFlag = -1;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		sql = DBSQLite.getInstance(this);
		
		setContentView(R.layout.setting_bank_activity);
		
		setGoneTitle();
		
		listView = (ListView) findViewById(R.id.settingBankListView);
		insertButton = (Button) findViewById(R.id.settingBankbookInsertButton);
		resultView = getLayoutInflater().inflate(R.layout.view_no_result, null);
		
		insertButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(superContext, BankBookInsertActivity.class);
				startActivity(intent);
			}
		});
		
	}
	
	@Override
	protected void onResume()
	{
		super.onResume();
		// 데이터를 가져온다.
		new ShowDialog().execute(BDUtil.asyncFlag, 1);
	}
	
	private void setBankbook()
	{
		String query = "SELECT id, name, money, addflag, count " +
					   "FROM " +
					   "(SELECT b.id id, b.name name, b.money money, d.addflag addflag, d.count count " +
					   "FROM " +
					   "bankbook b, bankbook_detail d " +
					   "WHERE " +
					   "b.id = d.linkid and d.count > 0 " +
					   "ORDER BY d.count) " +
					   "UNION ALL " +
					   "SELECT id, name, money, addflag, count " +
					   "FROM " +
					   "(SELECT b.id id, b.name name, b.money money, d.addflag addflag, d.count count " +
					   "FROM " +
					   "bankbook b, bankbook_detail d " +
					   "WHERE " +
					   "b.id = d.linkid and d.count < 1 " +
					   "ORDER BY d.count);";
		
		sql.selectMapTile(superContext, query, new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				list = new ArrayList<BankbookData>();
				
				int idIdx = c.getColumnIndex("id");
				int nameIdx = c.getColumnIndex("name");
				int moneyIdx = c.getColumnIndex("money");
				int addflagIdx = c.getColumnIndex("addflag");
				int countIdx = c.getColumnIndex("count");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					BankbookData data = new BankbookData();
					data.setId(c.getString(idIdx));
					data.setName(c.getString(nameIdx));
					data.setMoney(c.getString(moneyIdx).replaceAll(",", ""));
					data.setFlag(c.getInt(addflagIdx) + "");
					data.setOrder(c.getInt(countIdx) + "");
					
					list.add(data);
					
					c.moveToNext();
				}
			}
		});
		
//		String query = "SELECT addflag, count, linkid " +
//				"FROM ( SELECT addflag, count, linkid FROM bankbook_detail " +
//				"WHERE count > 0 " +
//				"ORDER BY count ASC ) " +
//				"UNION ALL " +
//				"SELECT addflag, count, linkid " +
//				"FROM bankbook_detail " +
//				"WHERE count <= 0 ;"; 
//		
//		sql.selectMapTile(this, query, new ParseSelectData()
//		{
//			@Override
//			public void resultData(Cursor c)
//			{
//				list = new ArrayList<BankbookData>();
//				
//				int addflagIdx = c.getColumnIndex("addflag");
//				int orderIndex = c.getColumnIndex("count");
//				int linkidIndex = c.getColumnIndex("linkid");
//				addflag = -1;
//				order = -1;
//				linkid = -1;
//				c.moveToFirst();
//				
//				for (int i = 0; i < c.getCount(); i++)
//				{
//					addflag = c.getInt(addflagIdx);
//					order = c.getInt(orderIndex);
//					linkid = c.getInt(linkidIndex);
//					
//					sql.selectMapTile(superContext, "SELECT id, name, money FROM bankbook " +
//							"WHERE id = " + linkid + ";", 
//							new ParseSelectData()
//					{
//						@Override
//						public void resultData(Cursor c)
//						{
//							int idIndex = c.getColumnIndex("id");
//							int nameIndex = c.getColumnIndex("name");
//							int moneyIndex = c.getColumnIndex("money");
//							
//							c.moveToFirst();
//							
//							for (int i = 0; i < c.getCount(); i++)
//							{
//								BankbookData data = new BankbookData();
//								data.setId(c.getString(idIndex));
//								data.setName(c.getString(nameIndex));
//								data.setMoney(c.getString(moneyIndex));
//								
//								data.setOrder(order + "");
//								
//								if (addflag == 1)
//								{
//									data.setFlag("1");
//								}
//								else
//								{
//									data.setFlag("0");
//								}
//								
//								list.add(data);
//								
//								c.moveToNext();
//							}
//						}
//					});
//					
//					c.moveToNext();
//					
//				}
//			}
//		});
		
		ArrayList<BankbookData> tempList1 = new ArrayList<BankbookData>();
		ArrayList<BankbookData> tempList2 = new ArrayList<BankbookData>();
		
//		// order순으로 정렬
//		for (int i=0; i<list.size()-1; i++)
//		{
//			for (int j=i+1; j<list.size(); j++)
//			{
//				BankbookData data = new BankbookData();
//				
//				if ( (Integer.parseInt(list.get(i).getOrder()) > Integer.parseInt(list.get(j).getOrder()) ) )
//				{
////					BankbookData data1 = new BankbookData();
////					BankbookData data2 = new BankbookData();
////					
////					data1 = list.get(i);
////					data2 = list.get(j);
////					
////					list.set(i, data2);
////					list.set(j, data1);
//				}
//			}
//		}
		
		/////
		
		for (int i = 0; i < list.size(); i++)
		{
			BankbookData bData = new BankbookData();
			
			bData.setFlag(list.get(i).getFlag());
			bData.setId(list.get(i).getId());
			bData.setMoney(list.get(i).getMoney());
			bData.setName(list.get(i).getName());
			bData.setOrder(list.get(i).getOrder());
			
			if (bData.getFlag().equals("1"))
			{
				tempList1.add(bData);
			}
			else
			{
				tempList2.add(bData);
			}
		}
		
		list = null;
		
		list = new ArrayList<BankbookData>();
		
		BigDecimal money = BigDecimal.ZERO;
		
		for (int i = 0; i < tempList2.size(); i++)
		{
			money = money.add(new BigDecimal(tempList2.get(i).getMoney().replaceAll(",", "")));
		}
		
		if (money != BigDecimal.ZERO)
		{
			BankbookData temp1 = new BankbookData();
			temp1.setFlag("2");
			temp1.setName("자산포함총액");
			temp1.setMoney(money.toString());
			list.add(temp1);
		}
		
		list.addAll(tempList2);
		
		money = BigDecimal.ZERO;
		
		for (int i = 0; i < tempList1.size(); i++)
		{
			money = money.add(new BigDecimal(tempList1.get(i).getMoney().replaceAll(",", "")));
		}
		
		if (money != BigDecimal.ZERO)
		{
			BankbookData temp2 = new BankbookData();
			temp2.setFlag("3");
			temp2.setName("미포함총액");
			temp2.setMoney(money.toString());
			list.add(temp2);
		}
		
		list.addAll(tempList1);
	}
	
	private OnItemClickListener onItemClickListener = new OnItemClickListener()
	{
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int postion,
				long arg3)
		{
			data = null;
			data = list.get(postion);
			
			if (data.getFlag().equals("2") || data.getFlag().equals("3"))
			{
				return;
			}
			
			Intent intent = new Intent(superContext, BankBookUpdateActivity.class);
			intent.putExtra(BANKBOOK_DATA, data);
			startActivity(intent);
			
//			AlertDialog.Builder dia = new AlertDialog.Builder(BankMoneyActivitiy.this);
//			
//			dia.setTitle("통장 삭제/수정");
//			dia.setMessage("통장을 삭제하거나 수정 하실 경우 자동화에 연결된 내용도 변경됩니다.");
//			dia.setIcon(android.R.drawable.ic_dialog_info);
//			
//			dia.setPositiveButton("삭제", new DialogInterface.OnClickListener()
//			{
//				@Override
//				public void onClick(DialogInterface dialog, int which)
//				{
//					setDeleteData(data);
//					dialog.dismiss();
//				}
//			});
//			
//			dia.setNeutralButton("수정", new DialogInterface.OnClickListener()
//			{
//				@Override
//				public void onClick(DialogInterface dialog, int which)
//				{
//					setUpdateData(data);
//					dialog.dismiss();
//				}
//			});
//			
//			dia.setNegativeButton("취소", new DialogInterface.OnClickListener()
//			{
//				@Override
//				public void onClick(DialogInterface dialog, int which)
//				{
//					dialog.dismiss();
//				}
//			});
//			
//			dia.show();
		}
	};
	
	private void setDeleteData(final BankbookData data)
	{
		boolean checkFlag = getLinkCheckCard(data);
		
		boolean creditFlag = getLinkCreditCard(data);
		
		AlertDialog.Builder dialog = new AlertDialog.Builder(this);
		dialog.setTitle("경고");
		dialog.setIcon(android.R.drawable.ic_dialog_info);
		dialog.setMessage("연결된 카드를 변경하거나 삭제해 주세요. 통장이 삭제 될 경우 연결된 내역은 수정 삭제가 불가능합니다.");
		
		DialogInterface.OnClickListener onClickPositive = new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				Intent intent = new Intent(BankMoneyActivitiy.this, CheckCardActivity.class);
				intent.putExtra(LINK_CARD, true);
				intent.putExtra(CARD_ID, data.getId());
				startActivity(intent);
			}
		};
		
		DialogInterface.OnClickListener onClickNeutral = new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				Intent intent = new Intent(BankMoneyActivitiy.this, CreditCardActivity.class);
				intent.putExtra(LINK_CARD, true);
				intent.putExtra(CARD_ID, data.getId());
				startActivity(intent);
			}
		};
		
		if (checkFlag && creditFlag)
		{
			dialog.setPositiveButton("체크", onClickPositive);
			dialog.setNeutralButton("신용", onClickNeutral);
		}
		else if (checkFlag)
		{
			dialog.setPositiveButton("체크", onClickPositive);
		}
		else if (creditFlag)
		{
			dialog.setNeutralButton("신용", onClickNeutral);
		}
		
		dialog.setNegativeButton("취소", new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				dialog.dismiss();
			}
		});
		
		if (checkFlag || creditFlag)
		{
			dialog.show();
			return;
		}
		else
		{
			new ShowDialog().execute(BDUtil.asyncFlag, 3);
			return;
		}
	}

	private void setBankBookDeleteData(final BankbookData data)
	{
		String [] whereArgs = new String[]{data.getId()};
		sql.delete(this, "bankbook", "id = ?", whereArgs);
		
		// 동장 자동화 테이블도 같이 삭제 됩니다.
		sql.selectMapTile(this, "SELECT id FROM auto_bank WHERE moneykind = '"
				+ BDUtil.getApostrophe(data.getName()) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				ArrayList<String> ids = new ArrayList<String>();
				
				int idIdx = c.getColumnIndex("id");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					ids.add(c.getInt(idIdx) + "");
					c.moveToNext();
				}
				
				for (int j = 0; j < ids.size(); j++)
				{
					String id = ids.get(j);
					String [] whereArgs = new String[]{id};
					sql.delete(BankMoneyActivitiy.this, "auto_bank", "id = ?", whereArgs);
				}
			}
		});
		
		// 내통장이체 자동화 테이블도 같이 삭제 됩니다.
		sql.selectMapTile(this, "SELECT id FROM auto_mybank WHERE inkind = '"
				+ BDUtil.getApostrophe(data.getName()) + "' or outkind = '" 
				+ BDUtil.getApostrophe(data.getName()) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				ArrayList<String> ids = new ArrayList<String>();
				
				int idIdx = c.getColumnIndex("id");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					ids.add(c.getInt(idIdx) + "");
					c.moveToNext();
				}
				
				for (int j = 0; j < ids.size(); j++)
				{
					String id = ids.get(j);
					String [] whereArgs = new String[]{id};
					sql.delete(BankMoneyActivitiy.this, "auto_mybank", "id = ?", whereArgs);
				}
			}
		});
		
		// 통장데이터를 롤백한다.
		sql.selectMapTile(this, "SELECT money FROM bank_money;", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int moneyIdx = c.getColumnIndex("money");
//				int money = 0;
				BigDecimal money = BigDecimal.ZERO;
				
				c.moveToFirst();
				for (int i = 0; i < c.getCount(); i++)
				{
//					money = money + Integer.parseInt(c.getString(moneyIdx));
					money = money.add(new BigDecimal(c.getString(moneyIdx).replaceAll(",", "")));
					c.moveToNext();
				}
				
//				money = money - Integer.parseInt(data.getMoney());
				money = money.subtract(new BigDecimal(data.getMoney().replaceAll(",", "")));
				
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("money", money.toString());
				sql.update(BankMoneyActivitiy.this, "bank_money", map, null, null);
			}
		});
		
		// 총금액을 롤백한다.
		sql.selectMapTile(this, "SELECT money FROM total_money;", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int moneyIdx = c.getColumnIndex("money");
//				int money = 0;
				BigDecimal money = BigDecimal.ZERO;
				
				c.moveToFirst();
				for (int i = 0; i < c.getCount(); i++)
				{
//					money = money + Integer.parseInt(c.getString(moneyIdx));
					money = money.add(new BigDecimal(c.getString(moneyIdx).replaceAll(",", "")));
					c.moveToNext();
				}
				
//				money = money - Integer.parseInt(data.getMoney());
				money = money.subtract(new BigDecimal(data.getMoney().replaceAll(",", "")));
				
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("money", money.toString());
				sql.update(BankMoneyActivitiy.this, "total_money", map, null, null);
			}
		});
		
		// 통장에 연결된 내역들을 수정이나 삭제 못하게 막는다.
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("deleteyn", "1");
		String [] whereArgs1 = new String[]{
				BDConstents.BANK_TYPE, BDConstents.BANK_TYPE, data.getName()};
		sql.update(this, "in_out", map, "type = ? or linktype = ? and moneykind = ?", whereArgs1);
	}
	
	private void setUpdateData(final BankbookData data)
	{
		LayoutInflater li = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
		View view = li.inflate(R.layout.dialog_bankbook_insert, null);
		
		nameView = (EditText) view.findViewById(R.id.dialogBankbookName);
		moneyView = (EditText) view.findViewById(R.id.dialogBankbookMoney);
		EditTextInputFilter.filteringMoneyEditText(moneyView);
		
		AlertDialog.Builder dia = new AlertDialog.Builder(this);
		dia.setTitle("통장수정");
		dia.setIcon(android.R.drawable.ic_dialog_info);
		dia.setView(view);
		
		dia.setPositiveButton("수정", new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				setUpdateBankbook(data);
			}
		});
		
		dia.setNegativeButton("취소", new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				dialog.dismiss();
			}
		});
		
		dia.show();
		
		nameView.setText(data.getName());
		moneyView.setText(data.getMoney());
	}
	
	private void setUpdateBankbook(final BankbookData data)
	{
		if (nameView.getText().equals("") || nameView.getText().length() < 1)
		{
			BDUtil.showToast(BankMoneyActivitiy.this, "통장 이름을 입력해주세요.");
			return;
		}
		
		if (moneyView.getText().equals("") || moneyView.getText().length() < 1)
		{
			BDUtil.showToast(BankMoneyActivitiy.this, "금액을 입력해주세요.");
			return;
		}
		
		boolean nameOverlap = BDUtil.getOverlapCheck(sql, BankMoneyActivitiy.this, 
				"SELECT name FROM bankbook WHERE name = '" + 
						BDUtil.getApostrophe(nameView.getText().toString()) + "';");
		
		if (nameOverlap)
		{
			if (!nameView.getText().toString().equals(data.getName()))
			{
				BDUtil.showDialog(BankMoneyActivitiy.this, "확인", "동일한 통장 이름이 존재 합니다.");
				nameView.setText("");
				return;
			}
		}
		
		new ShowDialog().execute(BDUtil.asyncFlag, 4);
	}

	private void setBankMoneyUpdateData(final BankbookData data)
	{
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("money", BDUtil.getCommaDel(moneyView.getText().toString()));
		map.put("name", nameView.getText().toString());
		String [] whereArgs = new String[]{data.getId()};
		sql.update(this, "bankbook", map, "id = ?", whereArgs);
		
		// 통장 자동화 테이블도 같이 수정 됩니다.
		sql.selectMapTile(this, "SELECT id FROM auto_bank WHERE moneykind = '"
				+ BDUtil.getApostrophe(data.getName()) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				ArrayList<String> ids = new ArrayList<String>();
				
				int idIdx = c.getColumnIndex("id");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					ids.add(c.getInt(idIdx) + "");
					c.moveToNext();
				}
				
				for (int j = 0; j < ids.size(); j++)
				{
					String id = ids.get(j);
					
					HashMap<String, String> map = new HashMap<String, String>();
					map.put("moneykind", nameView.getText().toString());
					
					String [] whereArgs = new String[]{id};
					sql.update(BankMoneyActivitiy.this, "auto_bank", map, "id = ?", whereArgs);
				}
			}
		});
		
		// 내통장이체 자동화 테이블도 같이 수정 됩니다.
		sql.selectMapTile(this, "SELECT id FROM auto_mybank WHERE outkind = '"
				+ BDUtil.getApostrophe(data.getName()) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				ArrayList<String> ids = new ArrayList<String>();
				
				int idIdx = c.getColumnIndex("id");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					ids.add(c.getInt(idIdx) + "");
					c.moveToNext();
				}
				
				for (int j = 0; j < ids.size(); j++)
				{
					String id = ids.get(j);
					
					HashMap<String, String> map = new HashMap<String, String>();
					map.put("outkind", nameView.getText().toString());
					
					String [] whereArgs = new String[]{id};
					sql.update(BankMoneyActivitiy.this, "auto_mybank", map, "id = ?", whereArgs);
				}
			}
		});
		sql.selectMapTile(this, "SELECT id FROM auto_mybank WHERE inkind = '"
				+ BDUtil.getApostrophe(data.getName()) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				ArrayList<String> ids = new ArrayList<String>();
				
				int idIdx = c.getColumnIndex("id");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					ids.add(c.getInt(idIdx) + "");
					c.moveToNext();
				}
				
				for (int j = 0; j < ids.size(); j++)
				{
					String id = ids.get(j);
					
					HashMap<String, String> map = new HashMap<String, String>();
					map.put("inkind", nameView.getText().toString());
					
					String [] whereArgs = new String[]{id};
					sql.update(BankMoneyActivitiy.this, "auto_mybank", map, "id = ?", whereArgs);
				}
			}
		});
		
		// 통장 테이블을 롤백한다.
		sql.selectMapTile(this, "SELECT money FROM bank_money;", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int moneyIdx = c.getColumnIndex("money");
//				int money = 0;
				BigDecimal money = BigDecimal.ZERO; 
				
				c.moveToFirst();
				for (int i = 0; i < c.getCount(); i++)
				{
//					money = money + Integer.parseInt(c.getString(moneyIdx));
					money = money.add(new BigDecimal(c.getString(moneyIdx).replaceAll(",", "")));
					c.moveToNext();
				}
				
//				money = money - Integer.parseInt(data.getMoney());
				money = money.subtract(new BigDecimal(data.getMoney().replaceAll(",", "")));
				
//				money = money + Integer.parseInt(moneyView.getText().toString());
				money = money.add(new BigDecimal(moneyView.getText().toString().replaceAll(",", "")));
				
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("money", money.toString());
				sql.update(BankMoneyActivitiy.this, "bank_money", map, null, null);
			}
		});
		
		// 총금액을 롤백한다.
		sql.selectMapTile(this, "SELECT money FROM total_money;", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int moneyIdx = c.getColumnIndex("money");
//				int money = 0;
				BigDecimal money = BigDecimal.ZERO;
				
				c.moveToFirst();
				for (int i = 0; i < c.getCount(); i++)
				{
//					money = money + Integer.parseInt(c.getString(moneyIdx));
					money = money.add(new BigDecimal(c.getString(moneyIdx).replaceAll(",", "")));
					c.moveToNext();
				}
				
//				money = money - Integer.parseInt(data.getMoney());
				money = money.subtract(new BigDecimal(data.getMoney().replaceAll(",", "")));
				
//				money = money + Integer.parseInt(moneyView.getText().toString());
				money = money.add(new BigDecimal(moneyView.getText().toString().replaceAll(",", "")));
				
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("money", money.toString());
				sql.update(BankMoneyActivitiy.this, "total_money", map, null, null);
			}
		});
	}
	
	/**
	 * 통장에 연결된 체크카드가 있는지 가져온다.
	 * @param data
	 * @return
	 */
	private boolean getLinkCheckCard(BankbookData data)
	{
		checkCardFlag = false;
		
		sql.selectMapTile(this, "SELECT banklink FROM check_card WHERE banklink = "
				+ data.getId() + ";" , new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				if (c.getCount() > 0)
				{
					checkCardFlag = true;
				}
				else
				{
					checkCardFlag  = false;
				}
			}
		});
		
		return checkCardFlag;
	}
	
	/**
	 * 통장에 연결된 신용카드가 있는지 가져온다.
	 * @param data
	 * @return
	 */
	private boolean getLinkCreditCard(BankbookData data)
	{
		creditCardFlag = false;
		
		sql.selectMapTile(this, "SELECT banklink FROM credit_card WHERE banklink = "
				+ data.getId() + ";", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				if (c.getCount() > 0)
				{
					creditCardFlag = true;
				}
				else
				{
					creditCardFlag  = false;
				}
			}
		});
		
		return creditCardFlag;
	}
	
	private class BankBookAdapter extends ArrayAdapter<BankbookData>
	{
		private ArrayList<BankbookData> bankbookList;

		public BankBookAdapter(Context context, int textViewResourceId,
				ArrayList<BankbookData> list)
		{
			super(context, textViewResourceId, list);
			bankbookList = list;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent)
		{
			View v  = convertView;
			if (v == null)
			{
				LayoutInflater li = (LayoutInflater) getContext().getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
				v = li.inflate(R.layout.list_item_bankbook, null);
			}
			
			BankbookData data = bankbookList.get(position);
			TextView name = (TextView) v.findViewById(R.id.bankbookName);
			TextView money = (TextView) v.findViewById(R.id.bankbookMoney);
			TextView flag = (TextView) v.findViewById(R.id.bankbookFlag);
			
			name.setText(data.getName());
			money.setText(BDUtil.getWon(data.getMoney()) + shape);
			
			if (data.getFlag().equals("1"))
			{
				v.setBackgroundColor(0x00000000);
				flag.setTextColor(getResources().getColor(R.color.outmoney));
				flag.setText("X");
			}
			else if (data.getFlag().equals("0"))
			{
				v.setBackgroundColor(0x00000000);
				flag.setTextColor(getResources().getColor(R.color.inmoney));
				flag.setText("O");
			}
			else if (data.getFlag().equals("2"))
			{
				v.setBackgroundColor(getResources().getColor(R.color.bankbookcolor));
				flag.setTextColor(getResources().getColor(R.color.inmoney));
				flag.setText("O");
			}
			else if (data.getFlag().equals("3"))
			{
				v.setBackgroundColor(getResources().getColor(R.color.bankbookcolor));
				flag.setTextColor(getResources().getColor(R.color.outmoney));
				flag.setText("X");
			}
			
			return v;
		}
	}
	
	/**
	 * 다이얼로그 뛰우기 
	 */
	private class ShowDialog extends AsyncTask<Integer, Integer, Integer>{
		ProgressDialog dialog = null;
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			if (BDUtil.btnEnable)
			{
				BDUtil.btnEnable = false;
				BDUtil.asyncFlag = -1;
				
				dialog = new ProgressDialog(BankMoneyActivitiy.this);
				dialog.setCancelable(false);
				dialog.setMessage("Loading...");
				dialog.show();
			}
		}
		
		@Override
		protected Integer doInBackground(Integer... arg0) {
			
			if (arg0[0] == 0) {
				
				if (arg0[1] == 1)
				{
					setBankbook();
					
					return arg0[1];
				}
//				else if (arg0[1] == 2)
//				{
//					try
//					{
//						sql.beginTansaction(superContext);
//						
//						HashMap<String, String> map = new HashMap<String, String>();
//						map.put("name", name);
//						map.put("money", money);
//						
//						sql.insert(BankMoneyActivitiy.this, map, "bankbook");
//						
//						setTotalMoney();
//						
//						sql.setTransactionSuccessful();
//					} catch (Exception e)
//					{
//						return -1;
//					} finally {
//						try 
//						{
//							sql.endTransaction(superContext);
//						} catch (Exception e) 
//						{
//							return -1;
//						}
//					}
//					
//					return arg0[1];
//				}
//				else if (arg0[1] == 3) 
//				{
//					try
//					{
//						sql.beginTansaction(superContext);
//						
//						setBankBookDeleteData(data);
//						
//						sql.setTransactionSuccessful();
//					} catch (Exception e)
//					{
//						return -1;
//					} finally {
//						try 
//						{
//							sql.endTransaction(superContext);
//						} catch (Exception e) 
//						{
//							return -1;
//						}
//					}
//					
//					return arg0[1];
//				}
//				else if (arg0[1] == 4)
//				{
//					try
//					{
//						sql.beginTansaction(superContext);
//						
//						setBankMoneyUpdateData(data);
//						
//						sql.setTransactionSuccessful();
//					} catch (Exception e)
//					{
//						return -1;
//					} finally {
//						try 
//						{
//							sql.endTransaction(superContext);
//						} catch (Exception e) 
//						{
//							return -1;
//						}
//					}
//					
//					return arg0[1];
//				}
				
				return arg0[0];
				
			} else 
				return arg0[0];
		}
		
		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			
			if (dialog != null) {
				dialog.dismiss();
			}
			
			if (result == -1)
			{
				BDUtil.btnEnable = true;
				BDUtil.asyncFlag = 0;
				
				BDUtil.showDialog(superContext, "오류", "데이터 저장에 실패했습니다.");
			}
			else if (result == 1)
			{
				if (listView.getFooterViewsCount() > 0)
				{
					listView.removeFooterView(resultView);
				}
				
				if (list.size() < 1)
				{
					listView.addFooterView(resultView);
					listView.setFooterDividersEnabled(false);
					listView.setOnItemClickListener(null);
				}
				else
				{
					listView.setOnItemClickListener(onItemClickListener);
					listView.setFooterDividersEnabled(true);
				}
				
				adapter = new BankBookAdapter(BankMoneyActivitiy.this, R.layout.list_item_bankbook, list);
				listView.setAdapter(adapter);
				adapter.notifyDataSetChanged();
				
				BDUtil.btnEnable = true;
				BDUtil.asyncFlag = 0;
			}
//			else if (result == 2)
//			{
//				BDUtil.btnEnable = true;
//				BDUtil.asyncFlag = 0;
//				
//				BDUtil.showDialog(BankMoneyActivitiy.this, "추가완료", "통장이 추가 되었습니다.");
//				
//				new ShowDialog().execute(BDUtil.asyncFlag, 1);
//			}
//			else if (result == 3)
//			{
//				BDUtil.btnEnable = true;
//				BDUtil.asyncFlag = 0;
//				
//				BDUtil.showDialog(BankMoneyActivitiy.this, "삭제완료", "통장이 삭제 되었습니다.");
//				
//				new ShowDialog().execute(BDUtil.asyncFlag, 1);
//			}
//			else if (result == 4)
//			{
//				BDUtil.btnEnable = true;
//				BDUtil.asyncFlag = 0;
//				
//				BDUtil.showDialog(BankMoneyActivitiy.this, "수정완료", "통장이 수정 되었습니다.");
//				
//				new ShowDialog().execute(BDUtil.asyncFlag, 1);
//			}
		}
	}

	@Override
	protected void tipButton()
	{
	}
}
